package main

import (
	"fmt"
	"io"
	"os"
	"strconv"
)

func main() {
	srcFile := "/Users/dean/GoWorks/src/gomod/exercise/xk.png"
	destFile := "/Users/dean/GoWorks/src/gomod/exercise/xk-copy.png"
	tempFile := "/Users/dean/GoWorks/src/gomod/exercise/xk-temp.txt"

	file1, _ := os.Open(srcFile)
	file2, _ := os.OpenFile(destFile, os.O_RDWR|os.O_CREATE, os.ModePerm)
	file3, _ := os.OpenFile(tempFile, os.O_RDWR|os.O_CREATE, os.ModePerm)

	defer file1.Close()
	defer file2.Close()

	//业务
	file3.Seek(0, io.SeekStart)
	buf := make([]byte, 1024, 1024)
	n, _ := file3.Read(buf)
	countStr := string(buf[:n])
	fmt.Println("countStr:", countStr)

	count, _ := strconv.ParseInt(countStr, 10, 64)

	file1.Seek(0, io.SeekStart)
	file2.Seek(0, io.SeekStart)

	bufData := make([]byte, 1024, 1024)
	total := int(count)

	for {
		readnum, err := file1.Read(bufData) //readnum读到的数据
		if err == io.EOF {
			fmt.Println("读取完毕")
			file3.Close()
			os.Remove(tempFile)
			break
		}
		writenum, _ := file2.Write(bufData[:readnum])
		total += writenum

		file3.Seek(0, io.SeekStart)
		file3.WriteString(string(total))

	}
}
